package nuist.hanniko.stu.webbackend.service.impls;

import nuist.hanniko.stu.webbackend.dao.mapper.LwM2mDeviceMapper;
import nuist.hanniko.stu.webbackend.model.LwM2m.LwM2mDevice;
import nuist.hanniko.stu.webbackend.service.DeviceBriefService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
public class DeviceBriefServiceImpl implements DeviceBriefService {

    @Autowired
    private LwM2mDeviceMapper lwM2mDeviceMapper;

    @Override
    public List<LwM2mDevice> getDevicesByIndex(int start, int length) {
        return lwM2mDeviceMapper.getDeviceByIndex(start, length);
    }

    @Override
    public List<LwM2mDevice> getAllDevice() {
        return lwM2mDeviceMapper.getAllDevice();
    }

    @Override
    public List<LwM2mDevice> getDeviceByType(String type) {
        return lwM2mDeviceMapper.getByType(type);
    }

    @Override
    public LwM2mDevice getByDeviceId(String deviceId) {
        return lwM2mDeviceMapper.getByDeviceId(deviceId);
    }

    @Override
    public int updateStateById(String deviceId, String state) {
        if (isExist(deviceId)) {
            lwM2mDeviceMapper.updateStateById(deviceId, state);
            return SUCCESS;
        }
        return FAILURE;
    }

    @Override
    public int updateRegistration(String deviceId, Date upTime) {
        if (isExist(deviceId)) {
            lwM2mDeviceMapper.updateRegistration(deviceId, upTime);
            return SUCCESS;
        }
        return FAILURE;
    }

    @Override
    public int insertOrUpdate(LwM2mDevice device) {
        if (isExist(device.getDeviceId())) {
            lwM2mDeviceMapper.update(device);
        } else {
            lwM2mDeviceMapper.insert(device);
        }

        return SUCCESS;
    }

    private boolean isExist(String deviceId) {
        return !(lwM2mDeviceMapper.getByDeviceId(deviceId) == null);
    }
}
